package com.hundsun.yr.universal.p2p.ui.activity;

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;

import com.ansen.http.net.HTTPCaller;
import com.hundsun.mobile.zwgt.BuildConfig;
import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.base.BaseAppManager;
import com.hundsun.yr.universal.library.common.PackageUtils;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.widget.HSTabLayout;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.library.widget.NoScrollViewPager;
import com.hundsun.yr.universal.p2p.HsApplication;
import com.hundsun.yr.universal.p2p.bean.AliasTagBean;
import com.hundsun.yr.universal.p2p.bean.BankAccountBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Container;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.impl.MainInteractorImpl;
import com.hundsun.yr.universal.p2p.presenter.base.Presenter;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.BaseTabPresenterImpl;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseFragment;
import com.hundsun.yr.universal.p2p.ui.adapter.MainPagerAdapter;
import com.hundsun.yr.universal.p2p.ui.fragment.HomeFragment;
import com.hundsun.yr.universal.p2p.ui.fragment.MineFragment;
import com.hundsun.yr.universal.p2p.ui.fragment.ProductFragment;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.BaseTabView;
import com.qiyukf.unicorn.utils.update.UtilsApp;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import io.github.lizhangqu.coreprogress.ProgressUIListener;

import static com.hundsun.mobile.zwgt.R.id.viewpager;

/**
 * @version V1.0
 * @Title: MainActivity.java
 * @Description: 主界面
 * @date 2015-10-22 下午3:09:45
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class MainActivity extends BaseActivity implements BaseTabView, OnPageChangeListener , HSDialog.HSDialogOnItemClickListener {
    private ProgressDialog progressDialog;
    /**
     * 更新弹窗
     **/
    private HSDialog dialog_update = null;
    /**
     * 下载地址
     */
    private String downloadUrl = null;
    private boolean if_force = false;
    // private ViewPager viewPager;
    private View no_login_click;
    private HSTabLayout tabLayout;
    private Presenter mPresenter;
    private RequestPresenter mPresenter2;
    public NoScrollViewPager noScrollViewPager;
    private MainPagerAdapter adapter;
    private int id;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
    /**
     * 上次点击返回键时间
     **/
    private long mExitTime;
    /**
     * 检查更新Presenter
     **/
    private RequestPresenter mUpdate = null;
    /**
     * 当前版本号
     */
    private String versionName, currentVersion;
    /**
     * 分享评估
     */

    private HSDialog dialog = null;
    /**
     * 下载器
     */
    private DownloadManager downloadManager;
    private String zwgt_data;
    private boolean isNoTipsRiskAssenment = true;
    private int mPosition = 0;
    public boolean isfirstopen;

//    private LocationUtils locationUtils;


//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        super.onCreate(savedInstanceState);
//    }

    /**
     * BaseActivity--是否改变状态栏颜色
     *
     * @return
     */
    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    /**
     * BaseAppcompatActivity--获取bundle数据
     *
     * @param extras
     */
    @Override
    protected void getBundleExtras(Bundle extras) {
        // TODO Auto-generated method stub
        id = extras.getInt("BindCardActivity");
        isfirstopen = extras.getBoolean("ISFIRSTOPEN");
    }

    /**
     * BaseAppCompatActivity--设置Activity布局
     *
     * @return
     */
    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.act_main;
    }

    /**
     * BaseAppComPatActivity--当 eventbus 事件传递过来时调用，eventbus的注册与其取消注册在父类中已经实现
     *
     * @param eventCenter
     */
    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub

        switch (eventCenter.getEventCode()) {
            case Extras.ORDER_SUCCESS:
                noScrollViewPager.setCurrentItem(3);
                break;
            case Constants.EVENT_REFRESH_AUTOMATIC_LOGIN:
                automaticLogin();
                break;
            case Constants.EVENT_DATA_LOGIN:
                noScrollViewPager.setCurrentItem(3);
                setTagAndAlies();
                break;
            case Constants.EVENT_DATA_LOGIN_EXPIRED2:
                noScrollViewPager.setCurrentItem(0, false);
                break;
            case Extras.RECHARGE_SUCCESS_GO_TO_PROJECT:
                noScrollViewPager.setCurrentItem(1);
                break;
            case Extras.RECHARGE_SUCCESS_GO_TO_LOAN:
                noScrollViewPager.setCurrentItem(2);
                break;
        }
    }

    /**
     * BaseAppCompatActivity--获取绑定的loading试图--将它返回给加载试图容器VaryViewHelperController--进行展示
     *
     * @return
     */
    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        return noScrollViewPager;
    }

    /**
     * BaseAppCompatActivity--初始化view并且绑定监听
     */
    @SuppressWarnings("deprecation")
    @Override
    protected void initViewsAndEvents() {
        versionName = PackageUtils.getVersionName(this);
         currentVersion = mConfigSP.getShareProf("server_version");

        if (versionName == null || currentVersion == null){
            return;
        }
        if (compareVersion(currentVersion, versionName)) {
            showUpdataDialog(true);
        }


        BaseAppManager instance = BaseAppManager.getInstance();
        if ((HsApplication.isSrcreenOn || HsApplication.goGesture) && (ifGoGeture() || ifGoFingerprintLockActivity())) {
            HsApplication.goGesture = false;
            HsApplication.isSrcreenOn = false;
        }

//        setSystemBarTintDrawable(getResources().getDrawable(ThemeUtils.getStatusbar_color()));
        noScrollViewPager = (NoScrollViewPager) findViewById(viewpager);
        noScrollViewPager.setNoScroll(true);
        tabLayout = (HSTabLayout) findViewById(R.id.tabs);
        tabLayout.setSmoothScroll(false);
        /**在这里将fragment传递进来进行添加到activity里面**/
        mPresenter = new BaseTabPresenterImpl(this, this, new MainInteractorImpl());
        mPresenter.initialized();

        //打开mainActivity并且处于登陆的时候，自动登录一次
        mPresenter2 = new InitializePresenterImpl(mContext, this);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter2.loadingData(TaskConstants.TASK_BANK_ACCOUNT, getString(R.string.root_url_test) + getString(R.string.api_user_test) +
                TaskConstants.TASK_BANK_ACCOUNT, Constants.EVENT_BEGIN, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test)
                + TaskConstants.TASK_BANK_ACCOUNT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    /**
     * @param isForce 是否强制更新
     * @Description 弹出下载对话框
     */
    private void showUpdataDialog(boolean isForce) {
        this.if_force = isForce;
        String title = mContext.getString(R.string.update_title);
        String content;
            content = mContext.getString(R.string.update_content, currentVersion);

        dialog_update = new HSDialog(title, content,
                mContext.getString(R.string.cancel),
                mContext.getString(R.string.sure), mContext, this).setCancelable(!isForce);
        dialog_update.show();

    }

    /**
     * 比较版本号
     *
     * @param version1 版本1
     * @param version2 版本2
     * @return boolean
     */
    public boolean compareVersion(String version1, String version2) {

        if (!TextUtils.isEmpty(version1) && !TextUtils.isEmpty(version2)) {

            String[] version1Array = version1.split("\\.");
            String[] version2Array = version2.split("\\.");

            if (version1Array != null && version1Array.length > 2
                    && version2Array != null && version2Array.length > 2) {

                for (int i = 0; i < version1Array.length; i++) {

                    int v1 = Integer.parseInt(version1Array[i]);
                    int v2 = Integer.parseInt(version2Array[i]);

                    if (v1 > v2) {
                        return true;
                    } else if (v1 < v2) {
                        return false;
                    }
                }
            }
        }
        return false;
    }
    private void automaticLogin() {
        if (sharedPreferences.getShareProf(UserInfo.TOKENID) != null && !sharedPreferences.getShareProf(UserInfo.TOKENID).isEmpty()) {
            zwgt_data = BaseRequestTool2.getFormatedDateString();
            JSONObject map = new JSONObject();
            try {
                map.put("token", sharedPreferences.getShareProf(UserInfo.TOKENID));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
            mPresenter2.loadingData(TaskConstants.TASK_LOGINSILENT, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_index_test)
                    + TaskConstants.TASK_LOGINSILENT, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_index_test)
                    + TaskConstants.TASK_LOGINSILENT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
        }
    }

//    private void riskEstimate() {
//        // TODO: 2017/6/14  确保用户已经开户的情况下才问用户是否已经做过风险评估，并且保证当前处于Homefragment
//        if (TextUtils.equals(sharedPreferences.getShareProf(UserInfo.USERLEVEL),"0")){
//            dialog = new HSDialog(getString(R.string.risk_login), getString(R.string.no_risk_assessment),
//                    getString(R.string.no_investment), getString(R.string.evaluate_immediately), mContext, MainActivity.this).setCancelable(false);
//            dialog.show();
//        }
//    }

    /**
     * BaseAppCompatActiviy--网络连接
     *
     * @param type
     */
    @Override
    protected void onNetworkConnected(NetType type) {
        // TODO Auto-generated method stub
        if (!Container.getInstance().isCheckVersion) {
            mUpdate.initialized();
        }
    }

    /**
     * BaseAppCompatActivity--网络错误
     */
    @Override
    protected void onNetworkDisConnected() {
        // TODO Auto-generated method stub

    }

    /**
     * 获取当前标签
     *
     * @return
     */
    public HSTabLayout getTabLayout() {
        return this.tabLayout;
    }

    /**
     * BaseAppCompatActivity--设置状态栏是否透明
     *
     * @return
     */
    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    /**
     * BaseAppCompatActivity--是否绑定event_bus
     *
     * @return
     */
    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return true;
    }

    /**
     * BaseAppCompatActivity--是否要动画
     *
     * @return
     */
    @Override
    protected boolean toggleOverridePendingTransition() {
        // TODO Auto-generated method stub
        return false;
    }

    /**
     * BaseAppCompatActivity--设置跳转动画枚举类型
     *
     * @return
     */
    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 绑定适配器
     *
     * @param viewPager
     * @param fragments
     */
    private void setupViewPager(ViewPager viewPager, List<BaseFragment> fragments) {
        adapter = new MainPagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
    }

    /**
     * BaseTabView--进来的时候mPresenter.initialized()--BaseTabPresenterImpl里面调用了initializeViews这个方法
     *
     * @param fragments
     * @param tabItem
     * @param titles
     */
    @Override
    public void initializeViews(List<BaseFragment> fragments, final List<View> tabItem, String[] titles) {
//        mUpdate = new CheckVersionPresenterImpl(mContext, this, this);
//        mUpdate.initialized();

        if (noScrollViewPager != null) {
            setupViewPager(noScrollViewPager, fragments);
        }

        if (fragments.size() > 0)
            noScrollViewPager.setOffscreenPageLimit(fragments.size() - 1);//设置加载页面

        tabLayout.setupWithViewPager(noScrollViewPager);
        noScrollViewPager.addOnPageChangeListener(this);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            HSTabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                if (id == 1) {
                    tab.setCustomView(tabItem.get(i), i == 3);
                    noScrollViewPager.setCurrentItem(3);
                } else {
                    tab.setCustomView(tabItem.get(i), i == 0);
                }
            }
        }


    }

    /**
     * 点击键盘
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Fragment fragment = adapter.getFragment(mPosition);
            if (fragment instanceof MineFragment) {
                if (((MineFragment) fragment).onKeyDown(keyCode, event)) {
                    return true;
                }
            } else if (fragment instanceof HomeFragment) {
                if (((HomeFragment) fragment).onKeyDown(keyCode, event)) {
                    return true;
                }
            } else if (fragment instanceof ProductFragment) {
                if (((ProductFragment) fragment).onKeyDown(keyCode, event)) {
                    return true;
                }
            }

            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
                return true;
            }

            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                showToast("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                HsApplication.getInstance().exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 关闭APP
     */
    public void exitApp() {
        BaseAppManager.getInstance().clear();
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @SuppressWarnings("deprecation")
    @Override
    public void onPageSelected(int position) {
        // TODO Auto-generated method stub
        //根据不同的页码设置不同的状态栏颜色
        mPosition = position;

//        if (position == 0 || position == 1){//如果fragment在homefragment或者productfragment的时候，显示一次风险评估
//            if (sharedPreferences.getShareProf(UserInfo.USERLEVEL) != null && TextUtils.equals(sharedPreferences.getShareProf(UserInfo.USERLEVEL),"0") && isNoTipsRiskAssenment){
//                //判断是否开户
//                if (sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT) != null && TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT), "YES") && !sharedPreferences.getBoolean(UserInfo.OLDUSER)){
//                    riskEstimate();
//                }
//                isNoTipsRiskAssenment = false;
//            }
//        }

        //设置背景颜色
//        if (position == 2) {
//            setSystemBarTintDrawable(getResources().getDrawable(R.color.loanlist_bg_cl));
//        } else {
//            if (!sharedPreferences.getBoolean(UserInfo.ISLOGIN)){
//                readyGo(LoginActivity.class);
//            }
//            noScrollViewPager.setCurrentItem(0);
//            setSystemBarTintDrawable(getResources().getDrawable(ThemeUtils.getStatusbar_color()));
//        }
    }
    private BankAccountBeen bankAccountBeen =null;
    @Override
    public <T> void initializeViews(String task_name, T data) {
        // TODO Auto-generated method stub
        switch (task_name){
            case TaskConstants.TASK_GETPUSHINFO:
                if (data != null) {
                    AliasTagBean aliasTagBean = (AliasTagBean) data;
                    JPushInterface.setAlias(this, 1, aliasTagBean.alias);
                    Set set = new HashSet();
                    set.addAll(aliasTagBean.tag);
                    JPushInterface.setTags(this, 1, set);
                }
                break;
            case TaskConstants.TASK_BANK_ACCOUNT:
                /**存储绑卡信息**/
                bankAccountBeen = (BankAccountBeen) data;
                if (bankAccountBeen.bankCard != null && !bankAccountBeen.bankCard.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.BANKCARD, bankAccountBeen.bankCard);
                    sharedPreferences.putShareProf(UserInfo.BANKCARDNAME, bankAccountBeen.bankName);

                    sharedPreferences.putShareProf(UserInfo.IF_BINDCARD, "YES");
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_BINDCARD, "NO");
                }
                break;
        }


    }

    /**
     * InitializeView--返回异常结果--不是很清楚
     *
     * @param task_name 任务名称
     * @param data
     * @param <T>
     */
    @Override
    public <T> void initializeError(String task_name, T data) {
        // TODO Auto-generated method stub
        if (TextUtils.equals(task_name, TaskConstants.TASK_FINISH)) {
            HsApplication.getInstance().exitApp();
        }
    }

//    @Override
//    public void onItemClick(Object o, int position) {
//        if ((HSDialog)o == dialog){
//            if (position != -1) {
//                //展示风险评估h5页面
//                zwgt_data = BaseRequestTool2.getFormatedDateString();
//                HashMap<String, String> hearder = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
//                        TaskConstants.TASK_RISKESTIMATE, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
//                HeaderMap headerMap = new HeaderMap();
//                headerMap.setMap(hearder);
//                Bundle bundle = new Bundle();
//                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.risk_estimate));
//                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, getString(R.string.root_h5_url_test) + getString(R.string.h5_user) + TaskConstants.TASK_RISKESTIMATE);
//                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap);
//                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
//                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
//                readyGo(WebRiskActivity.class, bundle);
//            }
//        }
//    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        no_login_click = findView(R.id.no_login_click);
        ViewGroup.LayoutParams lp = no_login_click.getLayoutParams();
        WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
        lp.width = (int) (wm.getDefaultDisplay().getWidth()*0.25);
        no_login_click.setLayoutParams(lp);

        if (!sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {
            tabLayout.canNotTouchLastPosition(true);
            no_login_click.setVisibility(View.VISIBLE);
            no_login_click.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    readyGo(LoginActivity.class);
                }
            });
        } else {
            tabLayout.canNotTouchLastPosition(false);
            no_login_click.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void setTagAndAlies(){
        if (sharedPreferences.getShareProf(UserInfo.TOKENID) != null && !sharedPreferences.getShareProf(UserInfo.TOKENID).isEmpty()) {
            zwgt_data = BaseRequestTool2.getFormatedDateString();
            JSONObject map = new JSONObject();
            try {
                map.put("a", "1");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
            mPresenter2.loadingData(TaskConstants.TASK_GETPUSHINFO, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_user_test)
                    + TaskConstants.TASK_GETPUSHINFO, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_user_test)
                    + TaskConstants.TASK_GETPUSHINFO, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
        }
    }

    @Override
    public void onItemClick(Object o, int position) {
        if ((HSDialog) o == dialog_update) {
            if (position != -1) {
                if (CommTool.getChannel(mContext).equals("P1OJDiTB")){
                    downloadUrl = mContext.getString(R.string.root_down_url) + "zwgt.apk";
                } else {
                    downloadUrl = mContext.getString(R.string.root_down_url)  + CommTool.getChannel(mContext) + "zwgt.apk";
                }
                startUpload(downloadUrl);//下载最新的版本程序
            }
            mConfigSP.putBoolean("isfirstcheckversion",false);
        }
    }
    /**
     * 开始下载
     * @param downloadUrl 下载url
     */
    private void startUpload(String downloadUrl){
        progressDialog=new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("正在下载新版本");
        progressDialog.setCancelable(false);//不能手动取消下载进度对话框

        final String fileSavePath= UtilsApp.getSaveFilePath(downloadUrl);
        HTTPCaller.getInstance().downloadFile(downloadUrl,fileSavePath,null,new ProgressUIListener(){

            @Override
            public void onUIProgressStart(long totalBytes) {//下载开始
                progressDialog.setMax((int)totalBytes);
                progressDialog.show();
            }

            //更新进度
            @Override
            public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
                progressDialog.setProgress((int)numBytes);
            }

            @Override
            public void onUIProgressFinish() {//下载完成
                Toast.makeText(MainActivity.this,"下载完成",Toast.LENGTH_LONG).show();
                progressDialog.dismiss();
                openAPK(fileSavePath);
            }
        });
    }

    /**
     * 下载完成安装apk
     * @param fileSavePath
     */
    private void openAPK(String fileSavePath){
        File file=new File(fileSavePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
            // "com.ansen.checkupdate.fileprovider"即是在清单文件中配置的authorities
            // 通过FileProvider创建一个content类型的Uri
            data = FileProvider.getUriForFile(this, "com.hundsun.mobile.zwgt.fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
        } else {
            data = Uri.fromFile(file);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
